package com.bjf.filter;

import java.io.IOException;
import java.util.Enumeration;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.bjf.common.ComCons;
import com.bjf.common.GlobalData;
import com.bjf.common.Module;
import com.bjf.common.Rescode;
import com.bjf.exception.BJFException;
import com.bjf.fmk.FreeMarkerConfiguration;

import freemarker.ext.beans.BeansWrapper;
import freemarker.ext.servlet.FreemarkerServlet;
import freemarker.template.Template;
import freemarker.template.TemplateExceptionHandler;
import freemarker.template.TemplateModel;
import freemarker.template.TemplateModelException;

public class FreemarkerFilter extends FreemarkerServlet {

	private static final long serialVersionUID = 2249078934502039390L;

    protected boolean preTemplateProcess(HttpServletRequest request,
            HttpServletResponse response, Template template, TemplateModel data)
            throws ServletException, IOException{
        try {
        	getConfiguration().setEncoding(request.getLocale(), "GBK");
        	getConfiguration().setDefaultEncoding("GBK");
            getConfiguration().setSharedVariable(ComCons.CONTEXT_PATH, request.getContextPath());
            
            try {
            	GlobalData.getFromRequest2(request);
            } catch(BJFException ex) {
            	ex.printStackTrace();
            }
        } catch (TemplateModelException e) {
            e.printStackTrace();
        }
        return super.preTemplateProcess(request, response, template, data);
    }

    public void init() throws ServletException {
        super.init();
        try{
            initConfiguration();
        }catch(BJFException asEx){
            asEx.printStackTrace();
            throw new ServletException(asEx);
        }
    }

    /**
     * init freemarker config
     * @throws BJFException
     */
    private void initConfiguration()throws BJFException{
        Enumeration keys = FreeMarkerConfiguration.getConfigKeys();
        String key = null;
        Object value = null;
        while(keys.hasMoreElements()){
            key = (String)keys.nextElement();
            value = FreeMarkerConfiguration.getConfigVal(key);
            try{
                getConfiguration().setSharedVariable(key, value);
            }catch(TemplateModelException tEx){
                throw new BJFException(Module.SYSTEM_MODULE,Rescode.FM_SERVLET_INIT_CONFIG_SETSV_ERROR,tEx);
            }
        }
        //config static functions
        getConfiguration().setSharedVariable(ComCons.STATICS,BeansWrapper.getDefaultInstance().getStaticModels());
        getConfiguration().setTemplateExceptionHandler(TemplateExceptionHandler.IGNORE_HANDLER);
        getConfiguration().setClassicCompatible(true);
    }
}
